 //
//  CLIndexModel.m
//  chanlin
//
//  Created by Ryan on 14-11-2.
//  Copyright (c) 2014年 chanlin. All rights reserved.
//

#import "CLIndexModel.h"
#import "IFCoreDataManager.h"
#import "NSManagedObject+Dao.h"
#import "NSObject+sagittarius.h"
#import "CLUrl.h"
#import "EColumn.h"

@implementation CLIndexModel

SGR_DEF_SINGLETION(CLIndexModel)

- (instancetype)init{
    self = [super init];
    if(self){
        self.pageNums=[NSMutableDictionary new];
    }
    return self;
}


- (void)getmagzineList:(NSDictionary *)category
               uiBlock:(void (^)(BOOL success,id responseObj,NSString *message) )block{
    __block BOOL isSuccess;
    __block NSString *errormessage;

    NSString *url=[category sgrGetStringForKey:@"url"];
    [self getWithUrl:url
               param:nil
           dataBlock:^(BOOL success, id responseObj, NSError *message, NSMutableDictionary *param) {
               if(success && [responseObj isKindOfClass:[NSDictionary class]]&&
                  1==[responseObj sgrGetIntForKey:@"status"]){
                    [[IFCoreDataManager sharedInstance] performBlockAndWait:^(NSManagedObjectContext *moc){
                        NSString *num=_safeStr([category sgrGetStringForKey:@"num"]);
                        NSArray *items=[EColumn fetchAllWithPredict:[NSPredicate predicateWithFormat:@"num==%@",num]
                                                           withMOC:moc];
                        for(CLList *item in items){
                            [moc deleteObject:item];
                        }
                        int columOrder=0;
                        NSArray *focus=[responseObj sgrGetArrayForKey:@"focus"];
                        if([focus count]>0){
                            EColumn *colum=[EColumn managerObjWithMoc:moc];
                            colum.num=num;
                            colum.order=columOrder++;
                            colum.cHeight=44.f;
                            
                            NSMutableOrderedSet *set=[NSMutableOrderedSet orderedSet];
                           
                            
                            CLList *focusItem=[CLList managerObjWithMoc:moc];
                            focusItem.itemId=@"focus";
                            focusItem.style=CLList_style_focus;
                            focusItem.cHeight=180.f;
                            focusItem.category=num;
                            focusItem.sort=0;
                            [set addObject:focusItem];
                             colum.book=set;
                            NSUInteger n=[focus count];
                            set=[NSMutableOrderedSet orderedSet];

                            for(int i=0;i<n;i++){
                                NSDictionary *dic=[focus sgrGetDictionaryForIndex:i];
                                if(!dic)continue;
                                CLList *listitem=[CLList managerObjWithMoc:moc];
                                [listitem proInitwithDictionary:dic];
                                listitem.style=CLList_style_doc;
                                listitem.category=@"focus";
                                
                                [set addObject:listitem];
                                //[focusItem addFocusObject:listitem];
                                
                            }
                            
                            if(set.count>0)
                                focusItem.focus=set;
                        }
                        
                        
                        NSArray *list=[((NSObject *)responseObj) sgrGetArrayForKey:@"list"];
                        NSUInteger n=[list count];
                        for(int i=0;i<n;i++){
                            NSDictionary *dic=[list sgrGetDictionaryForIndex:i];
                            EColumn *colum=[EColumn managerObjWithMoc:moc];
                            colum.num=num;
                            colum.order=columOrder++;
                            colum.cHeight=44.f;
                            colum.classId=[dic sgrGetStringForKey:@"classid"];
                            colum.name=[dic sgrGetStringForKey:@"classname"];
                             NSMutableOrderedSet *set=[NSMutableOrderedSet orderedSet];
                           
                            
                            NSArray *boobs=[dic sgrGetArrayForKey:@"book"];
                            NSUInteger m=[boobs count];
                            for(int i=0;i<m;i++){
                                NSDictionary *dic=[boobs sgrGetDictionaryForIndex:i];
                                
                                if(!dic)continue;
                                //NSString *itmeId=[dic sgrFGetStringForKey:@"id"];
                                
                                CLList *listitem=[CLList managerObjWithMoc:moc];
                                //listitem.sort=i+1+last;
                                [listitem proInitwithDictionary:dic];
                                listitem.category=num;
                                
                                NSArray *imgs=[dic sgrGetArrayForKey:@"morepic"];
                                if(imgs.count>0){
                                    if(listitem.subUrls){
                                        for(CLUrl *url in listitem.subUrls){
                                            [moc deleteObject:url];
                                        }
                                        NSMutableOrderedSet *set=[NSMutableOrderedSet orderedSet];
                                        for(NSString *str in imgs){
                                            CLUrl *url=[CLUrl managerObjWithMoc:moc];
                                            url.url=str;
                                            [set addObject:url];
                                            
                                        }
                                        listitem.subUrls=set;
                                        
                                    }
                                }
                                
                                [set addObject:listitem ];

                            }
                             colum.book=set;
                            
                        }
                        



                        [[IFCoreDataManager sharedInstance] saveContext:moc ToPersistentStore:nil];
                        isSuccess=YES;
                    }];
               }else{
                   isSuccess=NO;
                   errormessage=@"数据错误!";
                   
                   
               }
           } uiBlock:^(BOOL success, id responseObj, NSError *message, NSMutableDictionary *param) {
               block(isSuccess,responseObj,errormessage);
           }];
    
}

- (void)getListWithCategroy:(NSDictionary *)category
                   withPage:(int) num
                   lastList:(CLList *)clList
                    uiBlock:(void (^)(BOOL success,id responseObj,NSString *message) )block{
    if([@"1" isEqualToString:[category sgrGetStringForKey:@"tpl"]]||
       [@"2" isEqualToString:[category sgrGetStringForKey:@"tpl"]]){
        [self getSubListWithCategroy:category withPage:num lastList:clList uiBlock:block];
    }else{
        [self getCommListWithCategroy:[category sgrGetStringForKey:@"channelId"] withPage:num lastList:clList uiBlock:block];
    }
    
    
}

- (void)getSubListWithCategroy:(NSDictionary *)category
                       withPage:(int) num
                       lastList:(CLList *)clList
                        uiBlock:(void (^)(BOOL success,id responseObj,NSString *message) )block{
   // NSString *url=[NSString stringWithFormat:@"http://appv2.chanlin.org/e/app/clist.php?cid=%@&page=%d",category,num];
    
    NSString *url=[category sgrGetStringForKey:@"url"];
    url=[url stringByAppendingFormat:@"&page=%d",num];
    
    __block BOOL isSuccess;
    __block NSString *errormessage;
    [self getWithUrl:url param:nil dataBlock:^(BOOL success, id responseObj, NSError *message, NSMutableDictionary *param) {
        if(success && [responseObj isKindOfClass:[NSDictionary class]]&&
           1==[responseObj sgrGetIntForKey:@"status"]&&[responseObj sgrGetArrayForKey:@"list"].count>0){
            [[IFCoreDataManager sharedInstance] performBlockAndWait:^(NSManagedObjectContext *moc){
                int order=clList?clList.sort+1:0;
                if(num==1){
                NSArray *items=[CLList fetchAllWithPredict:[NSPredicate predicateWithFormat:@"category==%@",_safeStr([category sgrGetStringForKey:@"channelId"])]
                                                   withMOC:moc];
                for(CLList *item in items){
                    [moc deleteObject:item];
                }
                    
                    
                    
                    NSArray *focus=[((NSObject *)responseObj) sgrGetArrayForKey:@"focus"];
                    
                    if([focus count]>0){
                        CLList *focusItem=[CLList managerObjWithMoc:moc];
                        focusItem.itemId=@"focus";
                        focusItem.style=CLList_style_focus;
                        focusItem.cHeight=180.f;
                        focusItem.category=[category sgrGetStringForKey:@"channelId"];
                        focusItem.sort=-1;
                        NSUInteger n=[focus count];
                        
                        NSMutableOrderedSet *set=[NSMutableOrderedSet orderedSet];
                        
                        for(int i=0;i<n;i++){
                            NSDictionary *dic=[focus sgrGetDictionaryForIndex:i];
                            if(!dic)continue;
                            CLList *listitem=[CLList managerObjWithMoc:moc];
                            [listitem proInitwithDictionary:dic];
                            listitem.style=CLList_style_doc;
                            listitem.category=@"focus";
                            
                            [set addObject:listitem];
                            //[focusItem addFocusObject:listitem];
                            
                        }
                        
                        if(set.count>0)
                            focusItem.focus=set;
                    }

                    
                    
                    
                    
                }
                
                
                
                
                
                
                
                
                
                NSArray *list=[responseObj sgrGetArrayForKey:@"list"];
                NSUInteger n=[list count];
                
                for(int i=0;i<n;i++){
                    NSDictionary *dic=[list sgrGetDictionaryForIndex:i];
                    if(!dic)continue;
                    NSString *classId=[dic sgrGetStringForKey:@"classid"];
                    if(_isStrNotNull(classId)){
                        CLList *listitem=[CLList managerObjWithMoc:moc];
                        [listitem proInitwithClassDictionary:dic];
                        listitem.category=[category sgrGetStringForKey:@"channelId"];
                        listitem.sort=order++;
                    }
                    CLList *sub=[CLList managerObjWithMoc:moc];
                    [sub proInitwithDictionary:dic];
                    sub.category=[category sgrGetStringForKey:@"channelId"];
                    sub.sort=order++;
                }
                
                [[IFCoreDataManager sharedInstance] saveContext:moc ToPersistentStore:nil];
                isSuccess=YES;
            }];
        }else{
            isSuccess=NO;
            errormessage=@"数据错误!";


        }
    } uiBlock:^(BOOL success, id responseObj, NSError *message, NSMutableDictionary *param) {
        block(isSuccess,responseObj,errormessage);
    }];
}

- (void)getCommListWithCategroy:(NSString *)category
                   withPage:(int) num
                   lastList:(CLList *)clList
                    uiBlock:(void (^)(BOOL success,id responseObj,NSString *message) )block{
    NSString *url=nil;
    if([@"push" isEqualToString:category]){
        url=@"http://appv2.chanlin.org/e/app/push.php";
        if(num>1){
            url=[url stringByAppendingFormat:@"?page=%d",num];
        }
    }else{
        //url=[NSString stringWithFormat:[self urlWithCategory:@"list"],category,num];
       // NSLog(@"%@",[[CLGloble sharedInstance].menus sgrGetDictionaryForKey:category]);
         url=[[[CLGloble sharedInstance].menus sgrGetDictionaryForKey:category] sgrGetStringForKey:@"url"];
        url=[url stringByAppendingFormat:@"&page=%d",num];
    }
    NSAssert(url!=nil, @"url not be null");
    __block BOOL isSuccess;
    __block NSString *errormessage;
    [self getWithUrl:url param:nil dataBlock:^(BOOL success, id responseObj, NSError *message,NSMutableDictionary *param) {
        
        if(success && [responseObj isKindOfClass:[NSDictionary class]]&&
           1==[responseObj sgrGetIntForKey:@"status"]&&[responseObj sgrGetArrayForKey:@"list"].count>0){
            [[IFCoreDataManager sharedInstance] performBlockAndWait:^(NSManagedObjectContext *moc) {
                if(num==1){
                    NSArray *items=[CLList fetchAllWithPredict:[NSPredicate predicateWithFormat:@"category==%@",category]
                                                       withMOC:moc];
                    for(CLList *item in items){
                        [moc deleteObject:item];
                    }
                    NSArray *focus=[((NSObject *)responseObj) sgrGetArrayForKey:@"focus"];
                    
                    if([focus count]>0){
                        CLList *focusItem=[CLList managerObjWithMoc:moc];
                        focusItem.itemId=@"focus";
                        focusItem.style=CLList_style_focus;
                        focusItem.cHeight=180.f;
                        if([@"167" isEqualToString:category]){
                            focusItem.style=CLList_style_huabaoFocus;
                            focusItem.cHeight=180.f+40.f;
                        }
                        
                        focusItem.category=category;
                        focusItem.sort=-1;
                        NSUInteger n=[focus count];
                        
                        NSMutableOrderedSet *set=[NSMutableOrderedSet orderedSet];
                        
                        for(int i=0;i<n;i++){
                            NSDictionary *dic=[focus sgrGetDictionaryForIndex:i];
                            if(!dic)continue;
                            CLList *listitem=[CLList managerObjWithMoc:moc];
                            [listitem proInitwithDictionary:dic];
                            listitem.style=CLList_style_doc;
                            listitem.category=@"focus";
                            
                            [set addObject:listitem];
                            //[focusItem addFocusObject:listitem];
                            
                        }
                        
                        if(set.count>0)
                            focusItem.focus=set;
                    }
                    
                }
                NSArray *list=[((NSObject *)responseObj) sgrGetArrayForKey:@"list"];
                NSUInteger n=[list count];
                int last=clList?clList.sort+1:0;
                
                NSDictionary *comment = (NSDictionary *)[((NSObject *)responseObj) sgrGetDictionaryForKey:@"comments"];
                
                for(int i=0;i<n;i++){
                    NSDictionary *dic=[list sgrGetDictionaryForIndex:i];
                    if(!dic)continue;
                    NSString *itmeId=[dic sgrFGetStringForKey:@"id"];
                    //                    CLList *listitme=(CLList *)[CLList fetchWithPredict:
                    //                                                [NSPredicate predicateWithFormat:@"catagory=%@ and itemId=%@",category,itmeId]
                    //                                                      withMOC:moc];
                    //                    if(listitme )continue;
                    //                    listitme=[CLList managerObjWithMoc:moc];
                    CLList *listitem=[CLList managerObjByCreateOrGetWithPredicate:
                                      [NSPredicate predicateWithFormat:@"category==%@ and itemId==%@",category,itmeId]
                                                                              moc:moc];
                    listitem.sort=i+1+last;
                    
                    
                    listitem.category=category;
                    [listitem proInitwithDictionary:dic];
                    if([@"167" isEqualToString:category]){
                        listitem.style=CLList_style_huabao;
                        listitem.cHeight=128.f+56.f+12;
                    }
                    
                    NSDictionary *commentDic = (NSDictionary *)[comment sgrGetDictionaryForKey:listitem.itemId];
                    listitem.comment = [commentDic sgrGetIntForKey:@"comments"];
                    
                     NSArray *imgs=[dic sgrGetArrayForKey:@"morepic"];
                    if(imgs.count>0){
                        if(listitem.subUrls){
                            for(CLUrl *url in listitem.subUrls){
                                [moc deleteObject:url];
                            }
                            NSMutableOrderedSet *set=[NSMutableOrderedSet orderedSet];
                            for(NSString *str in imgs){
                                CLUrl *url=[CLUrl managerObjWithMoc:moc];
                                url.url=str;
                                [set addObject:url];

                            }
                            listitem.subUrls=set;
                            
                        }
                    }
                    
                }
                
                [[IFCoreDataManager sharedInstance] saveContext:moc ToPersistentStore:nil];
                isSuccess=YES;
                
            }];
        }else{
            isSuccess=NO;
            errormessage=@"数据错误!";
        }
    } uiBlock:^(BOOL success, id responseObj, NSError *message,NSMutableDictionary *param) {
        block(isSuccess,responseObj,errormessage);
    }];

}

- (void)deleteSearch{
    [[IFCoreDataManager sharedInstance] performBlock:^(NSManagedObjectContext *moc) {
        NSArray *items=[CLList fetchAllWithPredict:[NSPredicate predicateWithFormat:@"category==%@",@"search"]
                                           withMOC:moc];
        for(CLList *item in items){
            [moc deleteObject:item];
        }
        [[IFCoreDataManager sharedInstance] saveContext:moc ToPersistentStore:nil];
    }];
}

-(void)getSearchListWithKeyWord:(NSString *)keyWord
                        pageNum:(NSInteger)num
                        lsatObj:(CLList *)clList
                     uiBlock:(void (^)(BOOL success,id responseObj,NSString *message) )block {
    NSDictionary *paramDic = @{@"keyboard":(_isStrNotNull(keyWord)?keyWord:@""),
                               @"page":[NSString stringWithFormat:@"%ld",num]
                               };
    
    NSString  *url=@"http://appv2.chanlin.org/e/app/search.php?os=ios";
    
    NSString *category=@"search";
    NSAssert(url!=nil, @"url not be null");
    __block BOOL isSuccess;
    __block NSString *errormessage;
    [self getWithUrl:url param:paramDic dataBlock:^(BOOL success, id responseObj, NSError *message,NSMutableDictionary *param) {
        
        
        if(num==1){
            [[IFCoreDataManager sharedInstance] performBlockAndWait:^(NSManagedObjectContext *moc) {
                NSArray *items=[CLList fetchAllWithPredict:[NSPredicate predicateWithFormat:@"category==%@",category]
                                                   withMOC:moc];
                for(CLList *item in items){
                    [moc deleteObject:item];
                }
                [[IFCoreDataManager sharedInstance] saveContext:moc ToPersistentStore:nil];
            }];
        }
        
        
        if(success && [responseObj isKindOfClass:[NSDictionary class]]&&
           1==[responseObj sgrGetIntForKey:@"status"]&&[responseObj sgrGetArrayForKey:@"data"].count>0){
            [[IFCoreDataManager sharedInstance] performBlockAndWait:^(NSManagedObjectContext *moc) {
                if(num==1){
                                        NSArray *focus=[((NSObject *)responseObj) sgrGetArrayForKey:@"focus"];
                    
                    if([focus count]>0){
                        CLList *focusItem=[CLList managerObjWithMoc:moc];
                        focusItem.itemId=@"focus";
                        focusItem.style=CLList_style_focus;
                        
                        focusItem.cHeight=180.f;
                        if([@"167" isEqualToString:category]){
                            focusItem.style=CLList_style_huabaoFocus;
                            focusItem.cHeight=180.f+40.f;
                        }
                        
                        focusItem.category=category;
                        focusItem.sort=0;
                        NSUInteger n=[focus count];
                        
                        NSMutableOrderedSet *set=[NSMutableOrderedSet orderedSet];
                        
                        for(int i=0;i<n;i++){
                            NSDictionary *dic=[focus sgrGetDictionaryForIndex:i];
                            if(!dic)continue;
                            CLList *listitem=[CLList managerObjWithMoc:moc];
                            [listitem proInitwithDictionary:dic];
                            listitem.style=CLList_style_doc;
                            listitem.category=@"focus";
                            
                            [set addObject:listitem];
                            //[focusItem addFocusObject:listitem];
                            
                        }
                        
                        if(set.count>0)
                            focusItem.focus=set;
                    }
                    
                }
                NSArray *list=[((NSObject *)responseObj) sgrGetArrayForKey:@"data"];
                NSUInteger n=[list count];
                int last=clList?clList.sort+1:0;
                
                NSDictionary *comment = (NSDictionary *)[((NSObject *)responseObj) sgrGetDictionaryForKey:@"comments"];
                
                for(int i=0;i<n;i++){
                    NSDictionary *dic=[list sgrGetDictionaryForIndex:i];
                    if(!dic)continue;
                    NSString *itmeId=[dic sgrFGetStringForKey:@"id"];
               
                    CLList *listitem=[CLList managerObjByCreateOrGetWithPredicate:
                                      [NSPredicate predicateWithFormat:@"category==%@ and itemId==%@",category,itmeId]
                                                                              moc:moc];
                    listitem.sort=i+1+last;
                    
                    
                    listitem.category=category;
                    [listitem proInitwithDictionary:dic];
                    if([@"167" isEqualToString:category]){
                        listitem.style=CLList_style_huabao;
                        listitem.cHeight=128.f+56.f;
                    }
                    
                    NSDictionary *commentDic = (NSDictionary *)[comment sgrGetDictionaryForKey:listitem.itemId];
                    listitem.comment = [commentDic sgrGetIntForKey:@"comments"];
                    
                    NSArray *imgs=[dic sgrGetArrayForKey:@"morepic"];
                    if(imgs.count>0){
                        if(listitem.subUrls){
                            for(CLUrl *url in listitem.subUrls){
                                [moc deleteObject:url];
                            }
                            NSMutableOrderedSet *set=[NSMutableOrderedSet orderedSet];
                            for(NSString *str in imgs){
                                CLUrl *url=[CLUrl managerObjWithMoc:moc];
                                url.url=str;
                                [set addObject:url];
                                
                            }
                            listitem.subUrls=set;
                            
                        }
                    }
                    
                }
                
                [[IFCoreDataManager sharedInstance] saveContext:moc ToPersistentStore:nil];
                isSuccess=YES;
                
            }];
        }else{
            isSuccess=NO;
            errormessage=@"数据错误!";
        }
    } uiBlock:^(BOOL success, id responseObj, NSError *message,NSMutableDictionary *param) {
        block(isSuccess,responseObj,errormessage);
    }];
    

    
    
}

@end
